<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>IndexedDB 测试</title>
</head>
<body>
<h1>IndexedDB 测试</h1>


<script>
    const dbName = "indexedDB";
    const version = 1;

    connection(dbName, version, function (db) {
        const data = {name: '张三', mobile: '13333333333', age: 24, email: 'zhangsan@example.com'};
        putData(db, "db_table", data)
    }, function (e) {
        console.error("indexedDB 出现异常", e);
    })


    function connection(dbName, version, success, error) {
        // 加入兼容性配置
        window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
        // window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
        // window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
        if (!window.indexedDB) {
            alert("抱歉，您的浏览器无法支持本地缓存数据库，可能造成一些数据无法保存等情况");
        }
        // 连接 数据库 版本号必须是 Number
        const request = window.indexedDB.open(dbName, version);
        let database;
        // 连接失败触发
        request.onerror = function (event) {
            // 并不只是首次连接才会出现这个异常，而是只要有异常就会触发这里的事件
            error(event);
        }
        // 连接成功触发（首次）
        request.onupgradeneeded = function (event) {
            database = event.target.result;
            initConfig(database);
            success(database);
        };
        // 连接成功触发（非首次）
        request.onsuccess = function (event) {
            database = event.target.result;
            success(database);
        }
    }

    function initConfig(database) {
        // 初始化表 db_table 主键字段 id 自增长
        const table = database.createObjectStore("db_table", {keyPath: "id", autoIncrement: true});
        // 字段加索引 数据量大查询可以提高效率 unique是 true说明不允许重复
        table.createIndex("name", "name", {unique: false});
        table.createIndex("email", "email", {unique: true});
        table.createIndex("mobile", "mobile", {unique: true});
        const config = database.createObjectStore("db_config");
    }

    function putData(database, tableName, data, success, error) {
        // 增删改查必须用事务
        const transaction = database.transaction([tableName], "readwrite");
        const objectStore = transaction.objectStore(tableName);
        const idbValidKeyIDBRequest = objectStore.add(data);
        idbValidKeyIDBRequest.onsuccess = function (event) {

        }
        idbValidKeyIDBRequest.onerror = function (event) {

        }

        // 在所有数据添加完毕后的处理
        transaction.oncomplete = function (event) {
            success(event);
        };
        transaction.onerror = function (event) {
            error(event);
        };
    }


</script>
</body>
</html>